"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 数据库连接数大于用户连接数
Create At   : 2021/01/07
@zou_jialiang0505328126
Description :
    1.创建数据库，最大连接数为21
    2.创建普通用户，最大连接数为6
    3.使用该用户连接数据库，创建7个session
Expect      :
    1.创建数据库成功
    2.创建用户成功
    3.前6个连接正常，第7个连接报错
History     :
"""

import unittest
import time
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class DdlDatabase(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('--Opengauss_Reliability_Dbsys_Case230.py 开始执行--')
        self.db_primary_db_user = Node(node='PrimaryDbUser')
        self.constant = Constant()
        self.dbname = 'database_case230'
        self.tblname = 'tbl_case230'
        self.username = 'user_case230'
        self.password = 'test@2345234'

    def test_ddl_database(self):
        self.log.info('--1.创建数据库，最大连接数为21--')
        sql = f"drop database if exists {self.dbname};" \
            f"create database {self.dbname} with LC_COLLATE='zh_CN.gbk'" \
            f" LC_CTYPE = 'zh_CN.gbk' CONNECTION LIMIT=21;"
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS_MSG, result)

        self.log.info('--2.创建普通用户，最大连接数为6---')
        sql = f"drop user if exists {self.username};" \
            f"create user {self.username} with password '{self.password}'" \
            f" CONNECTION LIMIT 6;"
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_ROLE, result)
        time.sleep(15)

        self.log.info('---- 3.使用该用户连接数据库，创建7个session---')
        connect_thread = []
        for i in range(7):
            connect_thread.append(ComThread(
                self.commonshpri.executDbSql, args=(
                'select pg_sleep(120);', self.dbname,
                f'-U {self.username} -W {self.password}')))
            connect_thread[i].setDaemon(True)
            connect_thread[i].start()
            time.sleep(5)
        for i in range(7):
            connect_thread[i].join(400)
            result = connect_thread[i].get_result()
            self.log.info(result)
            if 6 == i:
                self.assertIn('too many', result)
            else:
                self.assertNotIn('too many', result)
        time.sleep(5)

        self.log.info('--------4.修改数据库最大连接数为3-----')
        sql = f"alter database {self.dbname} CONNECTION LIMIT 3;"
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertTrue('ALTER DATABASE', result)

        self.log.info('----5.使用该用户连接3个testdb，再连接一个tpcc---')
        connect_thread = []
        sql = 'select pg_sleep(120);'
        for i in range(4):
            if 3 == i:
                connect_thread.append(ComThread(self.commonshpri.executDbSql,
                args=(sql, self.db_primary_db_user.db_name,
                    f'-U {self.username} -W {self.password}')))
            else:
                connect_thread.append(ComThread(self.commonshpri.executDbSql,
                args=(sql, self.dbname,
                    f'-U {self.username} -W {self.password}')))
            connect_thread[i].setDaemon(True)
            connect_thread[i].start()
            time.sleep(5)
        for i in range(4):
            connect_thread[i].join(400)
            result = connect_thread[i].get_result()
            self.log.info(result)
            self.assertNotIn('too many', result)
        time.sleep(5)

    def tearDown(self):
        self.log.info('环境清理----')
        self.log.info('--删除数据库--')
        result = self.commonshpri.executDbSql(
            f"drop database if exists {self.dbname};")
        self.log.info(result)
        self.log.info('--删除用户--')
        result = self.commonshpri.executDbSql(
            f"drop user if exists {self.username};")
        self.log.info(result)
        self.log.info('Opengauss_Reliability_Dbsys_Case230.py 执行结束---')
